﻿/*
-----------------------------------------------------------------------------
This source file is part of Cell Cloud.

Copyright (c) 2009-2012 Cell Cloud Team (cellcloudproject@gmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "CellStableHeaders.h"
#include "CellSpeaker.h"
#include "CellBlockingConnector.h"
#include "CellPacket.h"
#include "CellMessage.h"
#include "CellNucleus.h"
#include "CellCryptologyImpl.h"
#include "CellTalkPacketDefinition.h"
#include "CellTalkService.h"
#include "CellSession.h"
#include "CellLoggerManager.h"

namespace cell
{

//---------------------------------------------------------------------------
Speaker::Speaker(const String& identifier)
	: mCelletIdentifier(identifier)
	, mAddress(NULL)
	, mHandler(NULL)
	, mConnector(NULL)
	, mHeartbeat(NULL)
	, mCalled(false)
	, mCount(0)
	, mTimestamp(0)
	, mHung(false)
{
	mHandler = CELL_NEW SpeakerConnectorHandler(this);
}
//---------------------------------------------------------------------------
Speaker::~Speaker(void)
{
	{
		CELL_LOCK_MUTEX(mHeartbeatMutex);

		if (NULL != mHeartbeat)
		{
			if (mHeartbeat->isRunning())
				mHeartbeat->stop();

			while (mHeartbeat->isRunning())
			{
				Thread::sleep(10);
			}

			CELL_DELETE mHeartbeat;
			mHeartbeat = NULL;
		}
	}

	if (NULL != mConnector)
	{
		mConnector->setHandler(NULL);

		if (mConnector->isConnected())
		{
			mConnector->disconnect();
		}

		CELL_DELETE mConnector;
		mConnector = NULL;
	}

	if (NULL != mHandler)
	{
		CELL_DELETE mHandler;
		mHandler = NULL;
	}

	if (NULL != mAddress)
	{
		if (mAddress->isIPv4())
		{
			CELL_DELETE static_cast<Inet4Address*>(mAddress);
		}
		else
		{
			CELL_DELETE static_cast<Inet6Address*>(mAddress);
		}
	}
}
//---------------------------------------------------------------------------
const String& Speaker::getCelletIdentifier(void) const
{
	return mCelletIdentifier;
}
//---------------------------------------------------------------------------
bool Speaker::call(const Inet4Address& address)
{
	CELL_LOCK_MUTEX(mConnectMutex);

	if (NULL != mConnector && mConnector->isConnected())
	{
		if (address.compare(mConnector->getSession()->getAddress()))
		{
			// 请求指定 Cellet
			requestCellet(mConnector->getSession());
			return true;
		}
	}

	if (NULL != mConnector)
	{
		mConnector->disconnect();

		CELL_DELETE mConnector;
		mConnector = NULL;
	}

	if (NULL != mAddress)
	{
		CELL_DELETE dynamic_cast<Inet4Address*>(mAddress);
	}
	mAddress = CELL_NEW Inet4Address(address);

	mConnector = CELL_NEW BlockingConnector();

	// 定义数据包标识
	char head[4] = {0x20, 0x10, 0x11, 0x10};
	char tail[4] = {0x19, 0x78, 0x10, 0x04};
	mConnector->defineDataMark(head, 4, tail, 4);

	mConnector->setHandler(mHandler);

	// 进行连接
	Session* session = mConnector->connect(address);
	if (NULL != session)
	{
		mNucleusTag = Nucleus::getSingleton().getTagAsString();

		mHung = false;

		return true;
	}
	else
	{
		return false;
	}
}
//---------------------------------------------------------------------------
void Speaker::hangup(void)
{
	if (NULL == mConnector)
	{
		return;
	}

	mHung = true;

	{
		CELL_LOCK_MUTEX(mHeartbeatMutex);

		if (NULL != mHeartbeat)
		{
			if (mHeartbeat->isRunning())
				mHeartbeat->stop();

			while (mHeartbeat->isRunning())
			{
				Thread::sleep(10);
			}

			CELL_DELETE mHeartbeat;
			mHeartbeat = NULL;
		}
	}

	mConnector->disconnect();

	CELL_DELETE mConnector;
	mConnector = NULL;
}
//---------------------------------------------------------------------------
bool Speaker::isCalled(void) const
{
	return mCalled;
}
//---------------------------------------------------------------------------
const InetAddress* Speaker::getAddress(void) const
{
	return mAddress;
}
//---------------------------------------------------------------------------
bool Speaker::speak(Primitive& primitive)
{
	Session* session = mConnector->getSession();

	// 处理消息不上锁
	if (NULL != session)
	{
		char* data = CELL_ALLOC_T(char, 8192, MEMCATEGORY_GENERAL);
		memset(data, 0x0, 8192);

		// 序列化原语
		SerializerStream pstream;
		primitive.write(pstream);
		String primitiveStream;
		pstream.str(primitiveStream);

		// 序列化后，原语入包
		char packetTag[5] = {0x0};
		TPT_DIALOGUE_ASSIGN(packetTag);
		Packet packet(packetTag, 99);
		packet.appendSubsegment(primitiveStream.c_str(), primitiveStream.length());
		packet.appendSubsegment(mNucleusTag.c_str(), mNucleusTag.length());

		// 数据打包
		uint length = Packet::pack(data, &packet);

		if (length > 0)
		{
			Message message(data, length);
			session->write(&message);
		}
		else
		{
			// 错误处理
			char log[128] = {0x0};
			sprintf(log, "[CC] Speaker talk with %s error: the message length is 0.", mCelletIdentifier.c_str());
			LoggerManager::getSingleton().log(log);
		}

		CELL_FREE(data, MEMCATEGORY_GENERAL);

		return true;
	}

	return false;
}
//---------------------------------------------------------------------------
int Speaker::getRetryCount(void) const
{
	return mCount;
}
//---------------------------------------------------------------------------
void Speaker::setRetryCount(int count)
{
	mCount = count;
}
//---------------------------------------------------------------------------
uint64 Speaker::getTimestamp(void) const
{
	return mTimestamp;
}
//---------------------------------------------------------------------------
void Speaker::setTimestamp(uint64 ts)
{
	mTimestamp = ts;
}
//---------------------------------------------------------------------------
void Speaker::recordTag(const String& tag)
{
	mRemoteTag = tag;
}
//---------------------------------------------------------------------------
void Speaker::requestCheck(Packet* packet, Session* session)
{
	// 包格式：密文|密钥

	char ciphertext[32] = {0x0};
	uint clen = packet->getSubsegment(ciphertext, 0);
	char key[16] = {0x0};
	packet->getSubsegment(key, 1);

	// 解密
	char plaintext[32] = {0x0};
	int plen = Cryptology::getSingleton().simpleDecrypt(plaintext, ciphertext, clen, key);

	// 包格式：原文
	char ptag[5] = {0x0};
	TPT_CHECK_ASSIGN(ptag);
	Packet response(ptag, 1);
	response.appendSubsegment(plaintext, plen);

	// 发送数据包
	char* data = CELL_ALLOC_T(char, response.getTotalLength() + 1, MEMCATEGORY_GENERAL);
	memset(data, 0x0, response.getTotalLength() + 1);
	int len = Packet::pack(data, &response);
	Message message(data, len);
	session->write(&message);
	CELL_FREE(data, MEMCATEGORY_GENERAL);
}
//---------------------------------------------------------------------------
void Speaker::requestCellet(Session* session)
{
	// 包格式：Cellet标识串|标签

	char pt[5] = {0x0};
	TPT_REQUEST_ASSIGN(pt);
	Packet packet(pt, 2);

	packet.appendSubsegment(mCelletIdentifier.c_str(), mCelletIdentifier.size());
	packet.appendSubsegment(mNucleusTag.c_str(), mNucleusTag.length());

	// 发送数据包
	char* data = CELL_ALLOC_T(char, packet.getTotalLength() + 1, MEMCATEGORY_GENERAL);
	memset(data, 0x0, packet.getTotalLength() + 1);
	int len = Packet::pack(data, &packet);
	Message message(data, len);
	session->write(&message);
	CELL_FREE(data, MEMCATEGORY_GENERAL);
}
//---------------------------------------------------------------------------
void Speaker::startHeartbeat(Session* session)
{
	{
		CELL_LOCK_MUTEX(mHeartbeatMutex);

		if (NULL != mHeartbeat)
		{
			if (mHeartbeat->isRunning())
				mHeartbeat->stop();

			while (mHeartbeat->isRunning())
			{
				Thread::sleep(10);
			}

			CELL_DELETE mHeartbeat;
			mHeartbeat = NULL;
		}
	}

	// 启动心跳
	mHeartbeat = CELL_NEW SpeakerHeartbeat(session);
	mHeartbeat->start();

	// 标记为已调用
	mCalled = true;
}
//---------------------------------------------------------------------------
void Speaker::processDialogue(Packet* packet, Session* session)
{
	// 包格式：序列化的原语

	uint sublen = packet->getSubsegmentLength(0);
	char* pridata = CELL_ALLOC_T(char, sublen + 1, MEMCATEGORY_GENERAL);
	memset(pridata, 0x0, sublen + 1);
	packet->getSubsegment(pridata, 0);

	SerializerStream stream;
	stream << pridata;

	// 反序列化原语
	Primitive primitive(mRemoteTag);
	primitive.read(stream);

	fireDialogue(primitive);

	CELL_FREE(pridata, MEMCATEGORY_GENERAL);
}
//---------------------------------------------------------------------------
void Speaker::fireDialogue(const Primitive& primitive)
{
	TalkService::getSingleton().fireListenerDialogue(mRemoteTag, primitive);
}
//---------------------------------------------------------------------------
void Speaker::fireContacted(void)
{
	TalkService::getSingleton().fireListenerContacted(mRemoteTag);
}
//---------------------------------------------------------------------------
void Speaker::fireQuitted(void)
{
	mCalled = false;

	TalkService::getSingleton().fireListenerQuitted(mRemoteTag);
}
//---------------------------------------------------------------------------
void Speaker::fireSessionCreated(Session* session)
{
}
//---------------------------------------------------------------------------
void Speaker::fireSessionDestroyed(Session* session)
{
	if (mHung)
		return;

	TalkService::getSingleton().retrySpeaker(this);
}
//---------------------------------------------------------------------------
void Speaker::fireSessionOpened(Session* session)
{
}
//---------------------------------------------------------------------------
void Speaker::fireSessionClosed(Session* session)
{
	{
		CELL_LOCK_MUTEX(mHeartbeatMutex);

		if (NULL != mHeartbeat)
		{
			if (mHeartbeat->isRunning())
				mHeartbeat->stop();

			while (mHeartbeat->isRunning())
			{
				Thread::sleep(10);
			}

			CELL_DELETE mHeartbeat;
			mHeartbeat = NULL;
		}
	}

	fireQuitted();
}



//---------------------------------------------------------------------------
SpeakerHeartbeat::SpeakerHeartbeat(Session* session)
	: mSession(session)
	, mRunning(false)
	, mSpinning(false)
{
}
//---------------------------------------------------------------------------
SpeakerHeartbeat::~SpeakerHeartbeat(void)
{
}
//---------------------------------------------------------------------------
void SpeakerHeartbeat::run(void)
{
	mRunning = true;

	int count = 20;

	mSpinning = true;
	while (mSpinning)
	{
		if (count == 20)
		{
			CELL_LOCK_MUTEX(mMutex);

			if (mSession == NULL)
				continue;

			char pt[5] = {0x0};
			TPT_HEARTBEAT_ASSIGN(pt);
			Packet packet(pt, 99);

			// 发送数据包
			char* data = CELL_ALLOC_T(char, packet.getTotalLength() + 1, MEMCATEGORY_GENERAL);
			memset(data, 0x0, packet.getTotalLength() + 1);
			int len = Packet::pack(data, &packet);
			Message message(data, len);
			mSession->write(&message);
			CELL_FREE(data, MEMCATEGORY_GENERAL);

			count = 0;
		}

		++count;

		Thread::sleep(1000);
	}

	mRunning = false;
}
//---------------------------------------------------------------------------
void SpeakerHeartbeat::stop(void)
{
	CELL_LOCK_MUTEX(mMutex);

	mSpinning = false;
	mSession = NULL;
}
//---------------------------------------------------------------------------
bool SpeakerHeartbeat::isRunning(void) const
{
	return mRunning;
}
} // end namespace cell
